'use strict';
exports.main = async (event, context) => {
	//event为客户端上传的参数
	console.log('event : ', event)
	const {
		funName
	} = event
	const db = uniCloud.database()
	const collection = db.collection('opendb-contacts')
	switch (funName) {
		case 'queryList':
			const queryListRes = await collection.limit(10).get() // 获取表中的10条数据，结果为json格式
			console.log(queryListRes);
			return queryListRes
			break;

		case 'add':
			const addRes = await collection.add({
				username: event.username,
				gender: event.gender,
				mobile: event.mobile,
				email: event.email,
				avatar: event.avatar
			})
			console.log(addRes);
			if (addRes.id) {
				return {
					code: 200,
					msg: '添加成功',
					data: null
				}
			} else {
				return {
					code: 444,
					msg: '添加失败',
					data: null
				}
			}
			break

		case 'del':
			const delRes = await collection.doc(event.id).remove()
			console.log(delRes);
			if (delRes.deleted) {
				return {
					code: 200,
					msg: '删除成功',
					data: null
				}
			} else {
				return {
					code: 444,
					msg: '删除失败',
					data: null
				}
			}
			break

		case 'findById':
			const findByIdRes = await collection.where({
				_id: event.id
			}).get()
			console.log(findByIdRes);
			return findByIdRes.data[0]
			break

		case 'edit':
			const editRes = await collection.doc(event.id).update({
				username: event.username,
				gender: event.gender,
				mobile: event.mobile,
				email: event.email,
				avatar: event.avatar
			})
			console.log(editRes);
			if(editRes.updated){
				return {
					code: 200,
					msg: '修改成功',
					data: null
				}
			} else {
				return {
					code: 444,
					msg: '修改失败',
					data: null
				}
			}
			break

		default:
			break;
	}
};
